/*!
 * Login.
 * Date: 2015/07/06.
 * Copyright© 2014-2015 Vamaker All Rights Reserved.
 */
require([
  'jquery',
  'formValidator',
  'formAjax',
  'languageMap',
  'notice'
], function ($, formValidator, formAjax, languageMap, notice) {
  $(function () {
    var dataFieldRule, options, dataValidator,
      forgetFieldRule, forgetOptions, forgetValidator,
      $dataFrm = $('#data-form'),
      $forgetFrm = $('#forget-form'),
      $loginContainer = $('.login-container'),
      $forgetContainer = $('.forget-container'),
      $forgetPwdBtn = $('#forget-pwd'),
      $forgetPwdBack = $('#forget-pwd-back'),
      $submitBtn = $dataFrm.find('button[type="submit"]'),
      $loginLoadingWrap = $('#login-loading-wrap'),
      $initTips = $('.init-loading-tips'),
      $loginTips = $('.login-loading-tips'),
      $verifycodeWrap = $dataFrm.find('.field-login-verifycode'),
      $verifycode = $('#verifycode'),
      $verifycodeImg = $('#verifycode-image'),
      $loginChecky = $('#login-checky'),
      $switchLanguage = $('#sys-lang-switch'),
      captchaRefreshUrl = VAM.getVar("CAPTCHA_REFRESH_URL"),
      switchLanguageUrl = VAM.getVar("SWITCH_LANGUAGE_URL"),
      urlParams = {}, retargetUrl,
      getUrlParam, refreshVerifyCode;
    getUrlParam = function () {
      var url = window.location.href,
        questionTag = url.indexOf('?'),
        paramArr = [],
        paramObj = {},
        sider = 0,
        paramResult= {};
      // console.log(url);
      if (questionTag === -1) {
        paramResult = {};
      } else {
        paramArr = url.substring(url.indexOf('?')+1, url.length).split('&');
        for (var i = 0, len = paramArr.length; i < len; i++) {
          var param = paramArr[i],
            urlKey = param.substring(0, param.indexOf('=')).toLowerCase(),
            urlValue = param.substring(param.indexOf('=')+1, param.length);
          paramObj[urlKey] = urlValue;
        };
        // console.log(paramObj);
        sider = paramObj['_sider'];
        delete paramObj['_sider'];
        paramResult = paramObj;
      };
      // console.log(paramResult);
      return paramResult;
    };
    refreshVerifyCode = function ($image) {
      var requestUrl;
      requestUrl = captchaRefreshUrl + '&_=' + (new Date()).getTime();
      $.get(requestUrl, function(data) {
        $image.prop('src', data.url)
      });
    };
    // Get retarget url.
    urlParams = getUrlParam();
    retargetUrl = window.decodeURIComponent(urlParams.retargeturl);
    // Captcha refresh.
    $verifycodeImg.on('click', function(evt) {
      var $me = $(this);
      evt.preventDefault();
      refreshVerifyCode($me);
    });
    // Language switch url.
    $switchLanguage.on('change', function(evt) {
      var meVal = $(this).val();
      evt.preventDefault();
      /* Act on the event */
      $.ajax({
        url: switchLanguageUrl,
        type: 'POST',
        dataType: 'JSON',
        data: {
          lang: meVal
        },
      })
      .done(function(data) {
        console.log(data);
        if (data.status === "success") {
          window.location.reload();
        };
      })
      .fail(function() {
        console.log("error");
      })
      .always(function() {
        console.log("complete");
      });
    });
    // Login checky.
    if (window.parseInt($loginChecky.val(), 10) >= 3) {
      $verifycodeWrap.show();
      $verifycode.val('');
    } else {
      $verifycodeWrap.hide();
      $verifycode.val('verifycode');
    }
    // console.log(retargetUrl);
    // console.log(typeof retargeturl)
    // Login Form.
    dataFieldRule = {
      'user_name': {
        rule: {
          required: {
            message: VAM.j('Email cannot be empty')
          },
          email: {
            message: VAM.j('Please enter the correct email address')
          },
          maxlength: {
            param: 60,
            message: VAM.j('The Email address up to 60 characters')
          }
        },
        messageContainer: 'user-name-err'
      },
      'user_pwd': {
        rule: {
          required: {
            param: 'password',
            message: VAM.j('Password cannot be empty')
          },
          password: {
            message: VAM.j('Password must be a character, Numbers')
          },
          minlength: {
            param: 6,
            message: VAM.j('Minimum password length of 6 characters')
          },
          maxlength: {
            param: 20,
            message: VAM.j('Password length up to 20 characters')
          }
        },
        messageContainer: 'user-pwd-err'
      },
      'verifycode': {
        rule: {
          required: {
            message: VAM.j('Verification code cannot be empty')
          },
        },
        messageContainer: 'verifycode-err'
      }
    };
    options = {
      submitOnSucceed: false,
      onvalidate: function (evt) {
        if (evt.resultList.length <= 0) {
          $dataFrm.ajaxSubmit({
            beforeSubmit: function () {
              $loginLoadingWrap.fadeIn('fast');
              $submitBtn.prop("disabled", true);
              // retargetUrl = getUrlParam()["retargetUrl"];
            },
            success: function (data) {
              $submitBtn.prop("disabled", false);
              if (data.status === 'success') {
                if (retargetUrl !== undefined && retargetUrl !== "undefined") {
                  window.location.href = retargetUrl;
                } else {
                  window.location.href = data.url;
                }
              } else {
                $loginLoadingWrap.fadeOut(function() {
                  VAM.errorMsg(data.message);
                  if (data.data["checky"] === true) {
                    $verifycodeImg.trigger('click');
                    $verifycodeWrap.show();
                    $verifycode.val('');
                  };
                });
              }
            }
          });
        }
      }
    };
    formValidator.validate($dataFrm, dataFieldRule, options);
    dataValidator = formValidator.dataValidator;
    // 对required重写，允许密码全为空格
    dataValidator.addRule('required', function(val, opt){
      if (opt==='password'){
          return !!(val&&!/^(?:\s\w|\u3000)+$/.test(val));
      } else{
          return !!(val&&!/^(?:\s|\u3000)+$/.test(val));
      }
    });

    // Forget Form.
    // forgetFieldRule = {
    //   'user-email': {
    //     rule: {
    //       required: {
    //         message: '邮箱不能为空'
    //       },
    //       email: {
    //         message: '请输入正确的邮箱'
    //       }
    //     },
    //     messageContainer: 'user-email-err'
    //   }
    // };
    // forgetOptions = {
    //   submitOnSucceed: true,
    //   onvalidate: function(evt) {
    //     if (evt.resultList.length <= 0) {}
    //   }
    // };
    // forgetValidator = new VAM.Checky($forgetFrm, forgetFieldRule, forgetOptions);

    // $forgetPwdBtn.on('click', function(evt) {
    //   evt.preventDefault();
    //   $loginContainer.hide();
    //   $forgetContainer.show();
    // });
    // $forgetPwdBack.on('click', function(evt) {
    //   evt.preventDefault();
    //   $loginContainer.show();
    //   $forgetContainer.hide();
    // });

    // Init page tips and submit button
    $loginTips.show();
    $initTips.hide();
    $submitBtn.prop('disabled', false);
    $loginLoadingWrap.hide();
  });
});
